package com.lottery.module.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lottery.pojo.BuyInfoDto;
import com.lottery.pojo.thrift.service.config.Sale;
import com.lottery.thrift.ThriftClient;
import com.lottery.util.FastJsonUtil;
import com.lottery.util.ListUtil;
import com.lottery.util.LotteryUtil;

@Service
public class LotterySaleService {
  public List<BuyInfoDto> buyNormal(List<BuyInfoDto> buyInfoDtos, String salePlace) {
    Assert.isTrue(!CollectionUtils.isEmpty(buyInfoDtos), "购买信息必填");
    Assert.isTrue(StringUtils.isNotBlank(salePlace), "销售地点必填");
    for (BuyInfoDto buyInfoDto : buyInfoDtos) {
      checkBuyInfo(buyInfoDto);
      buyInfoDto.setReds(LotteryUtil.sortIntegerList(buyInfoDto.getReds()));
      buyInfoDto.setBlues(LotteryUtil.sortIntegerList(buyInfoDto.getBlues()));
    }
    Map<String, Object> params = Maps.newHashMap();
    params.put("buyInfoDtos", buyInfoDtos);
    params.put("salePlace", salePlace);

    ThriftClient.callService(Sale.class, "lotterySaleService", "buyLottery", FastJsonUtil.bean2String(params));

    return buyInfoDtos;
  }

  private void checkBuyInfo(BuyInfoDto buyInfoDto) {
    Assert.isTrue((ListUtil.size(buyInfoDto.getReds()) >= 6) && (!ListUtil.hasSame(buyInfoDto.getReds())),
        "红球至少填写6个不能重复的数字");
    Assert.isTrue((ListUtil.size(buyInfoDto.getBlues()) >= 1) && (!ListUtil.hasSame(buyInfoDto.getBlues())),
        "蓝球至少填写1个不能重复的数字");
  }

  public List<BuyInfoDto> buyRandom(int count, String salePlace) {
    if (count < 1) {
      return null;
    }
    List<BuyInfoDto> buyInfoDtos = Lists.newArrayList();
    for (int i = 0; i < count; i++) {
      buyInfoDtos.add(LotteryUtil.generateLottery());
    }
    return buyNormal(buyInfoDtos, salePlace);
  }
}
